package com.emapp.lccode.mode

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.MutableLiveData
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.bean.AmapKey
import com.emapp.lccode.bean.UserKt
import com.emapp.lccode.http.NetworkApi
import com.emapp.lccode.http.apiService
import com.emapp.lccode.utils.XtomLogger
import com.emapp.lccode.utils.toEntity
import com.emapp.lccode.utils.toJsonStr
import com.hjq.toast.Toaster
import com.luck.picture.lib.thread.PictureThreadUtils
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.state.ResultState
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response

class LoginKtViewModel : BaseViewModel() {

    var user: MutableLiveData<UserKt?> = MutableLiveData()
    var code: MutableLiveData<ResultState<Any>> = MutableLiveData()
    var bitmap: MutableLiveData<Bitmap> = MutableLiveData()
    fun codeGet(username: String, img_verify: String) {
        request({ apiService.codeGet(username, img_verify) }, code, true)
    }

    fun image() {
        requestNoCheck({ apiService.imageCode() }, {
            val inputStream = it.byteStream()
            bitmap.postValue(BitmapFactory.decodeStream(inputStream))
        }, {
            Toaster.show(it.errorMsg)
        }, false, "")
    }

    fun login(username: String, verify_code: String, img_verify: String) {
        request({ apiService.login(username, verify_code, img_verify) },
            {
                val u: UserKt? = if (it is Collection<*>) null else it.toJsonStr().toEntity()
                user.postValue(u)
            }, {
                Toaster.show(it.errorMsg)
            }, true
        )
    }

    //    fun login(username: String, verify_code: String, img_verify: String) {
//        request({ apiService.login(username, verify_code, img_verify) }, { user },true)
//    }
    fun getImageCode() {
        image()
//        viewModelScope.launch {
//            downloadImage()
//        }
//         GlobalScope.launch(Dispatchers.Main) {
//             delay(1000L) // 延迟1秒
//             finish() // 关闭当前Activity
//         }

    }

    private fun downloadImage() {
        // 创建一个GET方式的请求结构
        val request: Request =
            Request.Builder().url(BaseConfig.ROOT_URL + "/api/appapi/addVerify").build()
        var c = OkHttpClient.Builder()
//        NetworkApi.INSTANCE.setHttpClientBuilder(c)
//        c.cookieJar(PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(appContext)))
        NetworkApi.INSTANCE.setHttpClientBuilder(c).build().newCall(request)
            .also {
                it.enqueue(object : Callback {
                    override fun onFailure(call: Call, e: okio.IOException) {
                        PictureThreadUtils.runOnUiThread { log_e("下载网络图片报错：" + e.message) }
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val inputStream = response.body!!.byteStream()
                        // 从返回的输入流中解码获得位图数据
                        bitmap.postValue(BitmapFactory.decodeStream(inputStream))
                    }
                })

            }
    }

    fun getDistrict(pid: String) {
        request({ apiService.getDistrict(pid) }, {
        }, {
        }, false)
    }

    var amapKey: MutableLiveData<AmapKey> = MutableLiveData()
    fun getAmapKey() {
        request({ apiService.getAmapKey() },
            {
                val intValue: ArrayList<AmapKey>? = if (it is Collection<*>) it.toJsonStr().toEntity() else null//it is Collection<*>判断是否为数组【】
                if (intValue.isNullOrEmpty()) {
                    amapKey.postValue(null)
                } else
                    amapKey.postValue(intValue[0])
            }, {
                amapKey.postValue(null)
            }, false
        )
    }

    protected val TAG = this.javaClass.simpleName
    protected open fun log_e(msg: String?) {
        if (BaseConfig.isDebug) XtomLogger.e(TAG, msg)
    }
}